package com.qing.qingcodegenerate.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qing.qingcodegenerate.exception.BusinessException;
import com.qing.qingcodegenerate.exception.ErrorCode;
import com.qing.qingcodegenerate.model.dto.user.UserLoginRequest;
import com.qing.qingcodegenerate.model.dto.user.UserQueryRequest;
import com.qing.qingcodegenerate.model.dto.user.UserRegisterRequest;
import com.qing.qingcodegenerate.model.entity.User;
import com.qing.qingcodegenerate.mapper.UserMapper;
import com.qing.qingcodegenerate.model.enums.UserRoleEnum;
import com.qing.qingcodegenerate.model.vo.UserVO;
import com.qing.qingcodegenerate.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.qing.qingcodegenerate.constant.UserConstant.USER_LOGIN_STATE;

/**
 *  服务层实现。
 *
 * @author 86157
 * @since 2025-08-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    @Override
    public Long userRegister(UserRegisterRequest request) {
// 2. 账号查重
        Long user =this.mapper.selectCountByQuery(new QueryWrapper().eq(User::getUserAccount, request.getUserAccount()));
        if(user>0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户已存在");
        }
// 3. 加密密码
        String encryptedPassword = getEncryptPassword(request.getUserPassword());
// 4. 保存用户信息
        User userEntity = new User();
        userEntity.setUserAccount(request.getUserAccount());
        userEntity.setUserPassword(encryptedPassword);
        userEntity.setUserName("无名氏");
        userEntity.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(userEntity);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败数据库错误");
        }

        return userEntity.getId();
    }
    @Override
    public String getEncryptPassword(String userPassword) {
// 盐值，混淆密码
        final String SALT = "qing";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }
    @Override
    public UserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 1. 加密密码
        String encryptedPassword = getEncryptPassword(userLoginRequest.getUserPassword());

        // 2. 查询用户信息
        User user = this.mapper.selectOneByQuery(new QueryWrapper()
                .eq(User::getUserAccount, userLoginRequest.getUserAccount())
                .eq(User::getUserPassword, encryptedPassword));

        if(user==null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户名或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return UserVO.objToVO(user);
    }
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }
    @Override
    public User getLoginUser(HttpServletRequest request) throws BusinessException {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        return QueryWrapper.create()
                .eq("id", id)
                .eq("userRole", userRole)
                .like("userAccount", userAccount)
                .like("userName", userName)
                .like("userProfile", userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null  || ObjUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(UserVO::objToVO).collect(Collectors.toList());
    }
}
